<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row class="btn">
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色用户列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开权限 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="['bborder', index == 0 ? 'tborder' : '']"
            >
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                  :class="[index1 == 0 ? '' : 'tborder']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeTag(scope.row, item1.id)"
                      >{{ item1.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      closable
                      @close="removeTag(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
              >删除</el-button
            >
            <el-button size="mini" type="warning" icon="el-icon-setting"
            @click="showTree(scope.row)"  >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分配权限框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="isroleDialog"
        width="50%"
        @close="clearDefKey"
      >
      <!-- 树形结构 -->
        <span>
            <el-tree :data="rolesData" :props="rolesProps" node-key="id"
            default-expand-all show-checkbox 
            :default-checked-keys="defkey"
            ref="checkRoles"
            ></el-tree>
        </span>
        <span slot="footer">
          <el-button @click="isroleDialog = false">取 消</el-button>
          <el-button type="primary" @click="allotRoles"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      isroleDialog: false,
      rolesData:[],
      rolesProps:{
          label: "authName",
          children: "children"
      },
      defkey: [],
      roleId: ''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取角色列表
    async getRolesList() {
      let { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      console.log(res);
      this.rolesList = res.data;
    },
    //删除角色权限
    removeTag(role, id) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .catch((err) => err)
        .then(async (confirm) => {
          console.log(confirm);
          if (confirm != "confirm") return this.$message.info("已取消删除");
          let { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${id}`
          );
          if (res.meta.status != 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          role.children = res.data;
        });
    },
    //获取权限数据
    async showTree(role){
     
        let {data:res} = await this.$http.get("rights/tree")
        if(res.meta.status != 200) return this.$message.error("获取失败")
        this.rolesData = res.data
        this.roleId = role.id
        this.getDefCheck(role,this.defkey)
        
        this.isroleDialog = true
        
    },
    //监听弹框，关闭时，清空id数组
    clearDefKey(){
      this.defkey = []
    },
    //使用递归函数，获取选中节点，和半选中节点
    getDefCheck(nodes,arr){
        if(!nodes.children){
          return arr.push(nodes.id)
        }

        nodes.children.forEach(item =>{
          this.getDefCheck(item,arr)
        })
    },   
    //分配权限
    async allotRoles(){
        let keys = [
          ...this.$refs.checkRoles.getCheckedKeys(),
          ...this.$refs.checkRoles.getHalfCheckedKeys()
        ]
        //console.log(keys)
        let idStr = keys.join(",")
        
        let {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(res.meta.status !=200) return this.$message.error("授权失败")
        this.$message.success("授权成功")
        this.getRolesList()
        this.isroleDialog = false
        

    }
  },
};
</script>

<style lang="less" scoped>
.btn {
  text-align: left;
  margin-bottom: 15px;
}
.el-table {
  font-size: 12px;

  .el-row {
    margin: 7px;
    display: flex;
    align-items: center;

    .el-tag {
      margin: 7px;
    }
  }
}

.tborder {
  border-top: 1px solid #ccc;
}

.bborder {
  border-bottom: 1px solid #ccc;
}
</style>